package com.bupt.websocket.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.auth0.jwt.interfaces.Claim;
import com.bupt.websocket.bean.LoginRes;
import com.bupt.websocket.bean.User;
import com.bupt.websocket.bean.WebSocketResult;
import com.bupt.websocket.utils.DisposableClient;
import com.bupt.websocket.utils.IkariUtils;
import com.bupt.websocket.utils.JwtToken;
import com.jyt.message.Message;
import com.jyt.message.MessageConfig;
import com.jyt.util.MySerializable;
import org.bouncycastle.asn1.ocsp.ResponseData;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Controller
public class UserController {

    @Value("${backhend_server_ip}")
    public String BACKHEND_SERVER_IP;
    //1-登录； 使用name、passwd登录，返回uid；
    //2-查看某个好友的详细信息；
    //3-获取好友列表；
    //4-发起添加好友申请
    //5-同意、拒绝好友申请
    //6-删好友；

    //1-登录； 使用name、passwd登录，返回uid；
    @RequestMapping("logging")
    @ResponseBody
    public String login(@RequestParam String name, @RequestParam String passwd) {
        String entityName = name + "logging";
        String requestType = "login";
        String myRequest = "{'name':'" + name + "','passwd':'" + passwd + "'}";
        String serviceName = "sys_login";
        String responseType = "loginRes";
        String myResponse = requestToBack(entityName, requestType, myRequest, serviceName, responseType);

        WebSocketResult webSocketResult=null;
        if (myResponse.contains("yes")) {
            LoginRes loginRes = JSON.parseObject(myResponse, new TypeReference<LoginRes>() {
            });
            String uid = loginRes.getUid();
            webSocketResult = new WebSocketResult(true);
            webSocketResult.uid = uid;
           return "{\"success\":\"yes\",\"uid\":\""+uid+"\"}";
        } else {
            webSocketResult = new WebSocketResult(false);
            return "{\"success\":\"no\",\"uid\":\"-\",\"message\":\"pleage logging\"}";
        }
       // return new WebSocketResult(true);
    }

    //2-查看某个好友的详细信息；
    @RequestMapping("fetchSomeFriend")
    @ResponseBody
    public String fetchSomeFriend(@RequestParam("friendname") String fname) {

        String entityName = fname + "fetchUserInfo";
        String requestType = "fetchUserInfo";
        String request = "{'name':'" + fname + "'}";
        String serviceName = "sys_userinfo";
        String responseType = "fetchUserInfo";

        String response = requestToBack(entityName, requestType, request, serviceName, responseType);
        /*Object parse = JSONObject.parse(response);
        response = JSON.toJSONString(parse);*/
        return response;
    }

    //3-获取好友列表；
    @RequestMapping("fetchFriendsList")
    @ResponseBody
    public String fetchFriends(@RequestParam String uid) {
        String entityName = uid + "fetchFris";
        String requestType = "fetchFris";
        String request = "{'uid':'" + uid + "'}";
        String serviceName = "sys_friends";
        String responseType = "fetchFris";

        String response = requestToBack(entityName, requestType, request, serviceName, responseType);
        /*Object parse = JSONArray.parse(response);
        response = JSON.toJSONString(parse);*/
        return response;
    }


    //4-发起添加好友申请
    @RequestMapping("addFri")
    @ResponseBody
    public WebSocketResult sendAddFriend(@RequestParam(value = "fid1") String fid1,
                                @RequestParam(value = "fid2") String fid2,
                                @RequestParam(value = "message") String message) {

        boolean isSuccess = IkariUtils.sendViWebPush(fid1, "sys_friends", "addFri", "{'fid1':'" + fid1 + "','fid2':'" + fid2 + "','message':'" + message + "'}");

        return new WebSocketResult(isSuccess);

    }

    //5-同意、拒绝好友申请
    @RequestMapping("addFriRes")
    @ResponseBody
    public WebSocketResult addFriRes(@RequestParam(value = "fid1") String fid1,
                            @RequestParam(value = "fid2") String fid2,
                            @RequestParam(value = "message") String message) {

        boolean isSuccess = IkariUtils.sendViWebPush(fid1, "sys_friends", "addFriRes", "{'fid1':'" + fid1 + "','fid2':'" + fid2 + "','message':'" + message + "'}");
        return new WebSocketResult(isSuccess);

    }

    //6-删好友；
    @RequestMapping("sendDeleteFri")
    @ResponseBody
    public WebSocketResult sendDeleteFri(@RequestParam String uid,
                                @RequestParam(value = "fid") String fid) {
        boolean isSuccess = IkariUtils.sendViWebPush(uid, "sys_friends", "delFri", "{'uid':'" + uid + "','fid':'" + fid + "'}");
        return new WebSocketResult(isSuccess);

    }


    public String requestToBack(String entityName, String requestType, String request, String responseName, String responseType) {

        Random random = new Random();
        String newEntityName = entityName + random.nextInt(2000);
        DisposableClient clientWeb = new DisposableClient(BACKHEND_SERVER_IP, MessageConfig.server_name, newEntityName, responseType);


        //注册客户端
        clientWeb.register(newEntityName);

        //重构请求:{'uid':'xxx', 'fid':'xxx'}（见接口文档）;
        //接受方:sys_friends（见接口文档）；

        byte[] bs;
        bs = MySerializable.object_bytes(request);
        Message msg = new Message(newEntityName, responseName, requestType, bs);
        //Message msg = new Message(entityName,"clientB","msg",bs);
        //发送请求;
        clientWeb.send(msg);
        //启动监听;
        String s = clientWeb.workString();
        clientWeb.unregister(newEntityName);
        clientWeb.shutdown();
        return s;
    }


}
